import type { UploadCustomRequestOptions } from 'naive-ui'
import CryptoJS from 'crypto-js'
import ossApi from '@/service/api/system/oss'
import axios from 'axios'
const getSing = async (options: UploadCustomRequestOptions, objectName, bucketName) => {
  const url = await ossApi.sign({
    bucketName,
    objectName,
  })
  axios
    .put(url, options.file.file, {
      headers: {
        'Content-Type': '',
      },
      onUploadProgress: (e) => {
        options.onProgress({
          percent: e.progress ? e.progress * 100 : 0,
        })
      },
    })
    .then((res) => {
      const { status } = res
      if ([200, 204].includes(status)) {
        const names = url.split('?')
        options.file.url = decodeURIComponent(names[0])
        nextTick(() => {
          options.onFinish()
        })
      } else {
        options.onError()
      }
    })
    .catch(() => {
      options.onError()
    })
}
export const uploadLocal = (
  options: UploadCustomRequestOptions,
  bucket = import.meta.env.VITE_IMG_BUCKET,
) => {
  const file = options.file.file
  const fr = new FileReader()
  fr.onloadend = function (e) {
    //  获取file后缀
    const oldName = file?.name || ''
    const names = oldName.split('.')
    const append = names.at(-1)
    const wordArray = CryptoJS.lib.WordArray.create(e.target?.result)
    const md5Hash = CryptoJS.MD5(wordArray).toString()
    const newName = `${md5Hash}.${append}`
    getSing(options, newName, bucket)
  }
  if (file) {
    fr.readAsArrayBuffer(file)
  }
}
